(function ($) {
	var today = ''; //今天
	var thisYM = '';//今天所属年月
	var currYM = '';//当前页面的年月
	var currIndex = 1;
	var pageType = '',loginID = ''
	var sourceData
	var PageDataArr = []
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	function getServerTime(){
		today = getCurrentDeviceDay()
		var ymDict = getYMDWithStr(today)
		thisYM = outYMStr(ymDict.year,ymDict.month);
		mui('#ymText')[0].innerText = outChinaYMStr(ymDict.year,ymDict.month)
		currYM = thisYM
		initSliderItemUI();
	}
	function updateDateBodyUI(year, month,domId){
		var maxDay = getMonthMaxDay(year, month);
		var lastMaxDay = getLastMonthMaxDay(year, month);
		var ymStr = outYMStr(year, month)
		var startIndex = getWeekIndex(ymStr + '-01');//1到7
		var endIndex = getWeekIndex(ymStr + '-' + maxDay);
		var count = startIndex + maxDay + (6 - endIndex);
		var html = '';
		var lineCount = 0;
		for(var i = 0; i < count; i++) {
			var curIndex = i % 7
			if(i % 7 == 0) {
				html += '<tr class="trDay" data-row="'+lineCount+'">';
				lineCount += 1;
			}
			if(i < startIndex) { //上个月的
				var dayStr = lastMaxDay - startIndex + i + 1;
				var lmonth = month - 1;
				var lyear = year;
				if(lmonth == 0) {
					lmonth = 12;
					lyear -= 1;
				}
				var idStr = '' + lyear + '-' + lmonth + '-' + dayStr;
				if(lmonth < 10) {
					idStr = '' + lyear + '-0' + lmonth + '-' + dayStr;
				}
				html += '<td id="'+idStr+'" class="oneDay abnormal'+' date'+idStr+'" data-index="'+curIndex+'"><div>' + dayStr + '</div></td>';
			} else if(i >= startIndex + maxDay) { //下个月
				var nmonth = month + 1;
				var nyear = year;
				if(nmonth == 13) {
					nmonth = 1;
					nyear += 1;
				}
				var dayStr = (i - maxDay - startIndex + 1);
				var idStr = '' + nyear + '-' + nmonth + '-0' + dayStr;
				if(nmonth < 10) {
					idStr = '' + nyear + '-0' + nmonth + '-0' + dayStr;
				}
				html += '<td id="'+idStr+'" class="oneDay abnormal'+' date'+idStr+'" data-index="'+curIndex+'"><div>0' + dayStr + '</div></td>';
			} else {
				var monthStr = month + '';
				if (month < 10) {
					monthStr = '0'+month;
				}
				var dayStr = (i - startIndex + 1);
				if((i - startIndex + 1) < 10) {
					dayStr = '0' + dayStr
				}
				var idStr = '' + year +'-'+monthStr + '-' + dayStr;
				var classStr ="oneDay"
				if (idStr == '' + today) { //今天
					classStr = 'oneDay today'
				}
				html += '<td id="'+idStr+'" class="'+classStr+' date'+idStr+'" data-index="'+curIndex+'"><div>' + dayStr + '</div></td>';
			}
			if(i % 7 == 6) {
				html += '</tr>';
			}
		}
		var itemDom = $('#'+domId)[0];
		itemDom.setAttribute('data-ym',ymStr);
		var dateTable = itemDom.querySelector('.dateTable')
		mui('#'+domId).off('tap','.oneDay',oneDayTapped)
		dateTable.innerHTML = html;
		mui('#'+domId).on('tap','.oneDay',oneDayTapped)
		getTrainData(ymStr,domId,maxDay)
	}
	function oneDayTapped(){
		if(this.getAttribute('class').indexOf('abnormal') != -1){
			return //只有本月可以点击
		}
		
		var oldChosen = $('#slider .chosen')[0]
		if (oldChosen == this) {
			return;
		}
		this.classList.add('chosen')
		getBottomData(this.id)
		if (!oldChosen) {
			mui.trigger($('#downImg')[0],'tap');
		}else{
			oldChosen.classList.remove('chosen')
		}
		if (!$('.showDetail')[0]) {
			mui.trigger($('#downImg')[0],'tap');
		}
	}
	function getBottomData(dayStr){
		$("#bottomScroll")[0].innerHTML = ''
		var pdict = {'loginID':loginID,'stDate':dayStr, 'endDate':dayStr}
		var paramDict = {'method':'web.INMTeaComm:FindDrillReleaseSubList','params':JSON.stringify(pdict),'type':'RecQuery'}
		//console.log(JSON.stringify(pdict))
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result.msgcode != '1') {
				$("#bottomScroll")[0].innerHTML = result.msg
				return
			}
			
			if (result.data == undefined) {
				$("#bottomScroll")[0].innerHTML = 'data字段为空'
				return
			}
			updateBottomUI(result.data)
		}, function(errorStr) {
			$("#bottomScroll")[0].innerHTML = errorStr
		});
	}
	function updateBottomUI(dataArr){
		var html = ''
		for (var i = 0; i < dataArr.length; i++) {
			var dict = dataArr[i]
			if (dict['ReleaseWay'] == 'D'&&dict['OrderFlag'] != 'Y') { //线下未预约
				continue
			}
			var levelDesc = ''//H:院级,L:科级,W:病区
			var level = dict['ReleaseLevel']
			if (level == 'H') {
				levelDesc = '院级'
			}else if (level == 'L') {
				levelDesc = '科级'
			}else if (level == 'W') {
				levelDesc = '病区'
			}
			var wayDesc = dict['ReleaseWay'] == 'O'?'上':'下'
			var CoursesType = dict['CoursesType'] == 'Y'?'必':'选'
			html += '<div class="oneInfo">'+
				'<div class="dateArea">'+
				'<div class="infoSub">'+dict['StartDate']+'</div>'+
				'<div class="infoLine">-</div>'+
				'<div class="infoSub">'+dict['EndDate']+'</div></div>'+
				'<div class="seperateLine"></div>'+
				'<div class="textArea">'+
					'<div class="infoTitle">'+dict['ReleaseDesc']+'</div>'+
					'<div class="classInfo"><div>'+levelDesc+'</div><div>'+
						(dict['ReleaseDrillTypeDesc']||' ')+'</div><div>线'+wayDesc+'培训</div><div>'+
						CoursesType+'修</div><div>'+dict['DrillCredit']+'分</div></div>'+
				'</div></div>'
		}
		$("#bottomScroll")[0].innerHTML = html
	}
	function getTrainData(ymStr,domId,maxDay){
		var pdict = {'loginID':loginID,'stDate':ymStr+"-01", 'endDate':ymStr+"-"+maxDay}
		var paramDict = {'method':'web.INMTeaComm:FindDrillReleaseSubList','params':JSON.stringify(pdict),'type':'RecQuery'}
		//console.log(JSON.stringify(pdict))
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result.msgcode != '1') {
				//showNullTip(result.msg)
				return
			}
			
			if (result.data == undefined) {
				//showNullTip('data字段为空')
				return
			}
			var dataArr = result.data
			updateUI(dataArr,domId,ymStr)
		}, function(errorStr) {
			//$("#scroll")[0].innerHTML = ''
			//showNullTip(errorStr)
		});
	}
	
	function updateUI(arr,domId,ymStr){
		var currDom = $('#'+domId)[0]
		var AllDays = $('#'+domId)[0].querySelectorAll('.oneDay')
		var stId = AllDays[0].id
		var stYm = stId.substring(0,7)
		var endId = AllDays[AllDays.length - 1].id
		var endYm = endId.substring(0,7);
		AllDays = undefined;
		for (var i = 0; i < arr.length;i++) {
			var oneDict = arr[i]
			if (oneDict['ReleaseWay'] == 'D'&&oneDict['OrderFlag'] != 'Y') { //线下未预约
				continue
			}
			var title = oneDict.ReleaseDesc
			var startDate = oneDict.StartDate
			var endDate = oneDict.EndDate
			var startIndex = 0
			var classTr = createClassTr();
			var classTd = createClassTd();
			classTd.innerHTML = title
			var newDomClass = ''
			if (startDate > endDate) {
				endDate = startDate
			}
			if (endDate < today) {
				newDomClass = 'expire'
			}else if (endDate == today) { //即将结束
				newDomClass = 'willExpire'
			}else if(startDate <= today&&endDate >= today){ //进行中的
				newDomClass = 'going'
			}else{//还未开始
				newDomClass = 'notStart'
			}
			classTd.classList.add(newDomClass)
			var startClass = 'start'
			if (currDom.querySelector('.date'+startDate)) { //开始日期在界面上能找到
				startIndex = currDom.querySelector(".date"+startDate).getAttribute('data-index')
				classTd.classList.add('start')
				if (startIndex != 0) {
					var leftTd = document.createElement('td');
					leftTd.colSpan = startIndex;
					classTr.appendChild(leftTd)
				}
				
			}else{ //开始日期在界面上找不到
				startDate = stId;
				startClass = ''
			}
			var endClass = 'end';
			if (!currDom.querySelector('.date'+endDate)) { //结束日期不能找到 跨月份了
				endDate = endId;
				endClass = '';
			}
			var count = 1;
			if (startDate == endDate) {
				classTd.classList.add('end')
				classTr.appendChild(classTd);
				var tempday = getNextDay(startDate)
				var dom = currDom.querySelector('.date'+startDate)
				if (!dom) { //最后一行
					currDom.querySelector('tbody').appendChild(classTr)
				}else{
					currDom.querySelector('tbody').insertBefore(classTr,dom.parentNode)
				}
				continue
			}
			
			for (var j = 0; j < 42;j++) {
				count +=1
				var day = getNextDay(startDate)
				var dom = currDom.querySelector('.date'+day)
				if (!dom) {
					break;
				}
				if (dom.getAttribute('data-index') == '0') { //周日
					classTd.colSpan = count -1;
					classTr.appendChild(classTd)
					currDom.querySelector('tbody').insertBefore(classTr,dom.parentNode);
					classTr = createClassTr();
					classTd = createClassTd();
					classTd.innerText = title
					classTd.classList.add(newDomClass)
					count=1
				}
				if (day == endDate) {
					classTd.colSpan = count;
					if (endClass != '') {
						classTd.classList.add(endClass)
					}
					classTr.appendChild(classTd)
					var currRow = parseInt(dom.parentNode.getAttribute('data-row'))
					var nextRowDom = currDom.querySelector('tbody tr[data-row="'+(currRow+1)+'"]');
					if (!nextRowDom) {
						currDom.querySelector('tbody').appendChild(classTr)
					}else{
						currDom.querySelector('tbody').insertBefore(classTr,nextRowDom);
					}
					break;
				}
				startDate = day
			}
		}
	}
	
	function createClassTr(){
		var tr = document.createElement('tr')
		tr.classList.add('trClass')
		return tr
	}
	function createClassTd(){
		var td = document.createElement('td')
		td.classList.add('oneClass')
		return td
	}
	
	function createDom(color,type){
		var div = document.createElement('div')
		if (color && color!="") {
			div.style.background=color
		}
		div.classList.add('oneClass')
		if (type) {
			div.classList.add(type)
		}
		return div
	}
	function baseSetup(){
		$("#slider").slider().gotoItem(1,0);
		var perInfo = app.getState()
		loginID = perInfo.loginID
		getServerTime();//初始化日期
		
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		if (mui.os.plus) {
			var self = plus.webview.currentWebview()
			sourceData = self.sourceData;
			pageType = self.pageType;
		}
		if (pageType == 'examine') { //title
			$('.mui-title')[0].innerText = '考程表'
		}else{
			$('.mui-title')[0].innerText = '课程表'
		}
		$('#ymText')[0].addEventListener('tap',selectYearMonth)
		$('#classInfo').on('tap','#downImg',function(){
			// $('#'+currIndex+'Wrapper')[0].querySelector('.mui-scroll').style.height='100%'
			if (!$('.showDetail')[0]) {
				var oldChosen = $('#slider .chosen')[0]
				if (!oldChosen) {
					mui.toast('请选点击要查看的日期')
					return
				}
				$('.mui-content')[0].classList.add('showDetail')
				this.src="../dependence/teach/images/up.svg"
				// 将想要的日期滚动到顶部
			}else{
				$('.mui-content')[0].classList.remove('showDetail')
				var oldChosen = $('#slider .chosen')[0]
				if (oldChosen) {
					oldChosen.classList.remove('chosen')
				}
				mui('#slider .mui-scroll-wrapper').each(function (index,element) {
					$('#'+element.id).scroll().scrollTo(0,0,100)
				})
				this.src="../dependence/teach/images/down.svg"
			}
			// setTimeout(function(){
			// 	mui('#slider .mui-scroll-wrapper').each(function (index,element) {
			// 		if (element.querySelector('table').clientHeight > element.clientHeight) {
			// 			// element.querySelector('.mui-scroll').style.height='auto'
			// 		}else{
			// 			// element.querySelector('.mui-scroll').style.height='100%'
			// 		}
			// 	})
			// },200)
		});
		openBottomDrag();
		// 监听滚动
		var slider = document.getElementById('slider');
		slider.addEventListener('slide', sliderSlideAction);
	}
	function selectYearMonth() {
		var _self = $('#ymText')[0];
		if(_self.picker) {
			_self.picker.show(function(rs) {
				afterSelectYearMonth(rs.text)
				_self.picker.dispose();
				_self.picker = null;
				
			});
		} else {
			var optionsJson = '{"type":"month"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new $.DtPicker(options);
			_self.picker.show(function(rs) {
				afterSelectYearMonth(rs.text)
				_self.picker.dispose();
				_self.picker = null;
			});
		}
	}
	
	function afterSelectYearMonth(textStr){
		var ymDict = getYMDWithStr(textStr)
		currYM =  outYMStr(ymDict.year,ymDict.month)
		$('#ymText')[0].innerText = outChinaYMStr(ymDict.year,ymDict.month)
		initSliderItemUI();
		//更新当前页前后的页面
	}
	
	
	
	function sliderSlideAction(){
		if ($('.showDetail')[0]) {
			$('.mui-content')[0].classList.remove('showDetail')
			var oldChosen = $('#slider .chosen')[0]
			if (oldChosen) {
				oldChosen.classList.remove('chosen')
			}
			mui('#slider .mui-scroll-wrapper').each(function (index,element) {
				$('#'+element.id).scroll().scrollTo(0,0,100)
			})
			mui('#downImg')[0].src="../dependence/teach/images/down.svg"
		}
		var index = event.detail.slideNumber;
		refreshSliderItemUI(index)
	}
	
	function refreshSliderItemUI(index){
		var direction = 0
		if (currIndex == 0 && index == 2) { //右滑
			direction = -1
		}else if (currIndex == 2 && index == 0) { //左滑
			direction = 1
		}else if (currIndex > index) { //右滑
			direction = -1
		}else if (currIndex < index) { //左滑
			direction = 1
		}
		if (direction == 0) {
			return
		}
		var ymDict = getYMDWithStr(currYM)
		if (direction == 1) { //下月
			ymDict = getNextYMDict(ymDict.year,ymDict.month)
		}else{ //上月
			ymDict = getLastYMDict(ymDict.year,ymDict.month)			
		}
		//updateDateBodyUI(ymDict.year,ymDict.month,index);
		currYM =  outYMStr(ymDict.year,ymDict.month)
		$('#ymText')[0].innerText = outChinaYMStr(ymDict.year,ymDict.month)
		
		currIndex = index;
		if (direction == 1) { //左滑
			ymDict = getNextYMDict(ymDict.year,ymDict.month)
			if (index == 0) {
				updateDateBodyUI(ymDict.year,ymDict.month,1);
			}else if (index == 1) {
				updateDateBodyUI(ymDict.year,ymDict.month,2);
				$('#lastWrapper')[0].innerHTML = $('#2Wrapper')[0].innerHTML
			}else{
				updateDateBodyUI(ymDict.year,ymDict.month,0);
				$('#firstWrapper')[0].innerHTML = $('#0Wrapper')[0].innerHTML
			}
		}else{ //右滑
			ymDict = getLastYMDict(ymDict.year,ymDict.month)
			if (index == 0) {
				updateDateBodyUI(ymDict.year,ymDict.month,2);
				$('#lastWrapper')[0].innerHTML = $('#2Wrapper')[0].innerHTML
			}else if (index == 1) {
				updateDateBodyUI(ymDict.year,ymDict.month,0);
				$('#firstWrapper')[0].innerHTML = $('#0Wrapper')[0].innerHTML
			}else{
				updateDateBodyUI(ymDict.year,ymDict.month,1);
			}
		}
	}
	
	function initSliderItemUI(){
		var currDict = getYMDWithStr(currYM)
		updateDateBodyUI(currDict.year,currDict.month,currIndex);
		var nextDict = getNextYMDict(currDict.year,currDict.month)
		var lastDict = getLastYMDict(currDict.year,currDict.month)
		if (currIndex == 0) {
			updateDateBodyUI(nextDict.year,nextDict.month,1);
			updateDateBodyUI(lastDict.year,lastDict.month,2);
		}else if (currIndex == 1) {
			updateDateBodyUI(nextDict.year,nextDict.month,2);
			updateDateBodyUI(lastDict.year,lastDict.month,0);
		}else{
			updateDateBodyUI(nextDict.year,nextDict.month,0);
			updateDateBodyUI(lastDict.year,lastDict.month,1);
		}
		$('#firstWrapper')[0].innerHTML = $('#0Wrapper')[0].innerHTML
		$('#lastWrapper')[0].innerHTML = $('#2Wrapper')[0].innerHTML
	}
	
	function openBottomDrag(){
		var downBtn = $("#downBtn")[0]
		var classInfo = $('#classInfo')[0]
		var slider = $('#'+currIndex+'Wrapper')[0];
		var bottomH = classInfo.clientHeight;
		var downBtnHeight = downBtn.clientHeight
		var max = downBtnHeight - bottomH;
		var half = 0 - bottomH*0.5
		var downBottom = max
		var dateBottom = downBtnHeight
		downBtn.addEventListener('dragstart', function(e) {
			if (!$('.showDetail')[0]) {
				classInfo.style.bottom = max + 'px'
				slider.style.bottom = downBtnHeight + 'px'
			}else{
				classInfo.style.bottom = '0px'
				slider.style.bottom = bottomH +'px'
			}
		});
		downBtn.addEventListener('drag', function(e) {
			var tempB = downBottom - e.detail.deltaY;
			if (tempB < max) {
				tempB = max
			} else if (tempB > 0) {
				tempB = 0
			}
			classInfo.style.bottom = tempB + 'px';
			var dateB = dateBottom - e.detail.deltaY;
			if (dateB < downBtnHeight+10) {
				dateB = downBtnHeight+10
			} else if (dateB > bottomH+10) {
				dateB = bottomH+10
			}
			slider.style.bottom = dateB + 'px';
			var offset = slider.querySelector('table').clientHeight - slider.clientHeight
			if (offset > 0) {
				// slider.querySelector('.mui-scroll').style.height='auto'
				$('#'+currIndex+'Wrapper').scroll().scrollTo(0,-offset,0)
			}else{
				// slider.querySelector('.mui-scroll').style.height='100%'
			}
		});
		//触摸结束时的处理
		downBtn.addEventListener('dragend', function(e) {
			downBottom = parseInt(classInfo.style.bottom)
			dateBottom = parseInt(slider.style.bottom)
			classInfo.style = ""
			slider.style = ""
			if (downBottom > half) {
				$('.mui-content')[0].classList.add('showDetail')
				downBtn.querySelector('img').src="../dependence/teach/images/up.svg"
			}else{
				if ($('#slider .chosen')[0]) {
					$('#slider .chosen')[0].classList.remove('chosen')
				}
				$('.mui-content')[0].classList.remove('showDetail')
				downBtn.querySelector('img').src="../dependence/teach/images/down.svg"
				mui('#slider .mui-scroll-wrapper').each(function (index,element) {
					$('#'+element.id).scroll().scrollTo(0,0,100)
				})
			}
			mui('#slider .mui-scroll-wrapper').each(function (index,element) {
				// if (element.querySelector('table').clientHeight > element.clientHeight) {
				// 	element.querySelector('.mui-scroll').style.height='auto'
				// }else{
				// 	element.querySelector('.mui-scroll').style.height='100%'
				// }
			})
		});
	}
	
})(mui);